import service from "../service.js"

export default {
	config: {
		baseUrl: service.BaseUrl_up,
		header: {
			'Content-Type': 'application/json;charset=UTF-8',
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		data: {},
		method: "GET",
		dataType: "json",
		/* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		if (!options) {
			options = {}
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		options.timeout = 60000
		return new Promise((resolve, reject) => {
			let _config = null
			options.complete = (response) => {
				if (response.errMsg.indexOf("request:fail") != -1) {
					let data = {
						code: 500,
						data: null,
						msg: "网络开小差了，请检查网络"
					}
					resolve(data)
				} else if (response.errMsg == "request:ok") {
					let statusCode = response.statusCode
					response.config = _config
					if (this.interceptor.response) {
						let newResponse = this.interceptor.response(response)
						if (newResponse) {
							response = newResponse
						}
					}
					if (statusCode === 200) { //成功
						resolve(response);
					} else {
						reject(response)
					}
				} else {
					let data = {
						code: 500,
						data: null,
						msg: response.errMsg
					}
					resolve(data)
				}





			}
			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			uni.request(_config);
		});
	}
}
